package com.itelecom.oss.mobile.dao;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.net.Uri;
import android.util.Xml;
import android.view.InflateException;

import com.itelecom.oss.Constants;



public class ParserFlow {

	private HttpClient mClient;

	public ParserFlow() {
		HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme(Constants.API_REST_PROTOCOL, PlainSocketFactory.getSocketFactory(), Constants.API_REST_PORT));

        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);

        mClient = new DefaultHttpClient(manager, params);
	}

	public void executeRequest(HttpGet get, ResponseHandler handler) throws IOException {
        HttpEntity entity = null;
        HttpHost host = new HttpHost(Constants.API_REST_HOST, Constants.API_REST_PORT, Constants.API_REST_PROTOCOL);
        try {
            final HttpResponse response = mClient.execute(host, get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                entity = response.getEntity();
                final InputStream in = entity.getContent();
                handler.handleResponse(in);
            }
        } finally {
            if (entity != null) {
                entity.consumeContent();
            }
        }
	}

	public void parseResponse(InputStream in, ResponseParser responseParser) throws IOException {
        final XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(new InputStreamReader(in));

            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG &&
                    type != XmlPullParser.END_DOCUMENT) {
                // Empty
            }

            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription()
                        + ": No start tag found!");
            }

            String name = parser.getName();
            if (Constants.RESPONSE_TAG_RSP.equals(name)) {
                final String value = parser.getAttributeValue(null, Constants.RESPONSE_ATTR_STAT);
                if (!Constants.RESPONSE_STATUS_OK.equals(value)) {
                    throw new IOException("Wrong status: " + value);
                }
            }

            responseParser.parseResponse(parser);

        } catch (XmlPullParserException e) {
            final IOException ioe = new IOException("Could not parser the response");
            ioe.initCause(e);
            throw ioe;
        }
    }

	public static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e("#####", "Could not close stream", e);
            }
        }
    }

	public static Uri.Builder buildGetMethod(String method) {
        final Uri.Builder builder = new Uri.Builder();
        builder.path(Constants.API_REST_URL+method);//.appendQueryParameter(Constants.PARAM_API_KEY, Constants.API_KEY);
//        builder.path(Constants.API_REST_URL).appendQueryParameter(Constants.PARAM_API_KEY, Constants.API_KEY);
//        builder.appendQueryParameter(Constants.PARAM_METHOD, method);
        return builder;
    }


}